/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package olympicgamesgui;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Collections;
import javax.swing.*;
import javax.swing.border.EtchedBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import olympicgameslogic.Athlete;
import olympicgameslogic.Delegation;
import olympicgameslogic.LinkedList;

/**
 *
 * @author Fabio Mendonca
 */
public class DialogManageDelegation extends JFrame {

   private JPanel pNorte, pMod, pMbt, p1,p2;
   private JScrollPane painel1;
   private JLabel nome;
   private JTable tabela1;
   private JButton MBt1, MBt2, MBt3;
   private static int linha;
   private Delegation deleg;
   private ClassLoader cldr = this.getClass().getClassLoader();
   
/// variaveis para a tabela subsituir por dados recebidos em array
   String[] columnNames = {"ICO", "Name", "Sex","Total Medals", "Edition Medals"};
   private Athlete at_temp;
   private DefaultTableModel TableModel;
   
   private int ano;
   
   
   public DialogManageDelegation(String titulo, final Delegation deleg) {
      super(titulo);
      this.deleg=deleg;
      ano = deleg.getEdition().getYear();
      
      super.setIconImage(Toolkit.getDefaultToolkit().getImage(cldr.getResource("images/extra/icon.png")));
      setLayout(new BorderLayout());
      pNorte = new JPanel();
      pNorte.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
      nome = new JLabel();
      nome.setText(""+deleg.getCountry().toString() + " Edition: "+ deleg.getEdition().getYear());
      nome.setFont(new Font("Arial", Font.PLAIN + Font.BOLD, 20));
      String flag=deleg.getCountry().getCode();
      ImageIcon img = new ImageIcon(cldr.getResource("images/flags/"+flag+".png"));
      nome.setIcon(img);
      pNorte.add(nome);
      pNorte.setBackground(Color.WHITE);
      add(pNorte, BorderLayout.NORTH);

//barra com botões
      pMod = new JPanel(new BorderLayout());
      pMbt = new JPanel(new FlowLayout());
      MBt1 = new JButton("New Athlete", new ImageIcon(cldr.getResource("images/extra/user_add.png")));
      MBt2 = new JButton("Edit Athlete", new ImageIcon(cldr.getResource("images/extra/user_edit.png")));
      MBt3 = new JButton("Delete Athlete", new ImageIcon(cldr.getResource("images/extra/user_delete.png")));
      pMbt.add(MBt1);
      pMbt.add(MBt2);
      pMbt.add(MBt3);

//criar tabela atraves do arraylist           

      //Tabela fazer codigo para carregad dados relativos a um determinado país.   

      tabela1 = new JTable() {

	 public boolean isCellEditable(int rowIndex, int colIndex) {
	    return false; //Disallow the editing of any cell
	 }
         public Class getColumnClass(int column) {
	    if (column == 0) {
	       return ImageIcon.class;
	    }
	    return Object.class;
	    //return getValueAt(0, column).getClass();
	 }
      };
      TableModel = (DefaultTableModel) tabela1.getModel();
      TableModel.setColumnIdentifiers(columnNames);
      setUpTableData();

      JTableHeader header = tabela1.getTableHeader();
      header.setBackground(Color.DARK_GRAY);
      header.setFont(new Font("Arial", Font.BOLD, 12));
      header.setForeground(Color.WHITE);
      tabela1.setPreferredScrollableViewportSize(new Dimension(300, 70));
      tabela1.setFillsViewportHeight(true);
      tabela1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
      tabela1.getSelectionModel().addListSelectionListener(new DialogManageDelegation.RowListener3());
      tabela1.getTableHeader().setReorderingAllowed(false);

//construir painel para tab de atletas  
      pMod.add(pMbt, BorderLayout.NORTH);
      painel1 = new JScrollPane(tabela1);
      pMod.add(painel1, BorderLayout.CENTER);
      p1 = new JPanel(new BorderLayout());
      p1.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));
      p1.add(pMbt, BorderLayout.NORTH);
      p1.add(pMod, BorderLayout.CENTER);
      
      
//construir painel para tab de Equipas    Criar o P2 -------------------------------------
         
      
      
      p2 = new JPanel(new BorderLayout());
      //pbuttons =  nem JPa
	      
	      
	      
      JTabbedPane pCentroTab = new JTabbedPane(JTabbedPane.TOP,JTabbedPane.SCROLL_TAB_LAYOUT);
      pCentroTab.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));      
      
      pCentroTab.addTab("Athlete", null, p1,"Athlete");
      pCentroTab.addTab("Team", null, p2,"Team"); 
            
      add(pCentroTab, BorderLayout.CENTER);    
      

      
      
      setMinimumSize(new Dimension(450, 400));
      setSize(450, 400);
      setVisible(true);
      setDefaultCloseOperation(DISPOSE_ON_CLOSE);
      setLocationRelativeTo(null);


      addWindowListener(new WindowAdapter() {

	 @Override
	 public void windowClosing(WindowEvent e) {
	    dispose();
	 }
      });
//        Eventos dos botoões
      //Botão Criar novo        
      MBt1.addActionListener(new ActionListener() {

	 @Override
	 public void actionPerformed(ActionEvent e) {
	    DialogManageAthlete dmat = new DialogManageAthlete(DialogManageDelegation.this,"Add Athlete", null, DialogManageDelegation.this, deleg);
	    dmat.showJan();
	 }
      });

      //Botão editar 
      MBt2.addActionListener(new ActionListener() {

	 @Override
	 public void actionPerformed(ActionEvent e) {
	    if (at_temp != null) {
	    DialogManageAthlete dmat = new DialogManageAthlete(DialogManageDelegation.this,"Edit Athlete", at_temp, DialogManageDelegation.this, deleg);
	    dmat.showJan();
	    } else {
	       JOptionPane.showMessageDialog(DialogManageDelegation.this, "No Athlete Selected");
	    }
	 }
      }
);

      //Botão apagar 
      MBt3.addActionListener(new ActionListener() {
	 @Override
	 public void actionPerformed(ActionEvent e) {
            if (at_temp != null) {
              int i = JOptionPane.showConfirmDialog(DialogManageDelegation.this, "Delete User?", "Delete User",JOptionPane.YES_NO_OPTION,JOptionPane.YES_NO_OPTION);  
              if (i==JOptionPane.YES_OPTION) {
                  deleg.getAthleteList().remove(at_temp);
                  OlympicGamesGui.ap.getAthletes().remove(at_temp);
                  refreshTable();
                  JOptionPane.showMessageDialog(DialogManageDelegation.this, "Athlete Removed");
              }                  
	    } else {
	       JOptionPane.showMessageDialog(DialogManageDelegation.this, "No User Selected");
	    } 
	 }
      });

      addWindowListener(new WindowAdapter() {

	 @Override
	 public void windowClosing(WindowEvent e) {
	    dispose();
	 }
      });

   }

   private class RowListener3 implements ListSelectionListener {

      @Override
      public void valueChanged(ListSelectionEvent event) {
	 if (event.getValueIsAdjusting()) {
	    return;
	 }
	 linha = tabela1.getSelectedRow();
	 if (linha == -1) {
	    linha = 0;
	 } else {
	    for (Athlete at : deleg.getAthleteList()) {
	       if (tabela1.getValueAt(linha, 1).toString().equals(at.getName().toString())) {
		  at_temp = at;
	       }
	    }
	 }
      }
   }

   private void setUpTableData() {
      Object[][] data1 = new Object[deleg.getAthleteList().getSize()][columnNames.length];
         int i = 0;                                            
         LinkedList<Athlete> tempEd = deleg.getAthleteList();
	 Collections.sort(tempEd, new Athlete.NameSorter());
         for (Athlete s : deleg.getAthleteList()) {  
         ImageIcon img3 = new ImageIcon(cldr.getResource("images/flags/" + s.getNation().getCode()+ ".png"));
	 data1[i][0] = img3;
	 data1[i][1] = s.getName().toString();         
	 data1[i][2] = s.getSex().toString();  
	 data1[i][3] = s.getTotalMedals();
	 data1[i][4] = s.getTotalEditionMedals(deleg.getEdition());
	 
	 TableModel.addRow(data1[i]);
	 i++;
      }
      tabela1.setModel(TableModel);
   }

   public void refreshTable() {
      TableModel.setRowCount(0);
      tabela1.removeAll();
      setUpTableData();
   }
}

